import axios from "axios";
import Vue from "vue";

const isDev = process.env.NODE_ENV === "development";

// export const request = axios.create({
//   baseURL: isDev ? "https://bigdata-t.duiopen.com/" : "/"
// });

var token = document.cookie.replace(/(?:(?:^|.*;\s*)token\s*\=\s*([^;]*).*$)|^.*$/, "$1");

export const request = axios.create({
  baseURL: isDev ? "" : "/",
  headers: {
    post: {
      ["Content-Type"]: "application/json"
    },
    put: {
      ["Content-Type"]: "application/json"
    },
    Authorization: token
  }
});

request.interceptors.response.use(
  res => {
    if (res && res.status == 200) {
      let { data, headers } = res;
      // 流媒体
      if (headers["content-type"] === "application/octet-stream") return data;
      if (data.code === 0 && data.message === "ok") {
        //请求成功
        return data.data;
      } else {
        if (data.code === 401 || data.code === 403) {
          // token 过期或失效
          // location.href = location.origin + "/#/login";
        }
        // 请求失败，抛出失败信息
        Vue.prototype.$message({
          message: `请求出错：${data.message}`,
          type: "error"
        });
        throw data.message;
      }
    }
  },
  err => {
    Vue.prototype.$message({
      message: `请求出错：${err}`,
      type: "error"
    });
    throw err;
  }
);
